package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.mysql.jdbc.Connection;
import lombok.SneakyThrows;
import model.UserInfo;
import sun.awt.geom.AreaOp;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;
import util.SessionUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.rmi.server.UID;
import java.sql.PreparedStatement;

/**
 * @author shkstart
 * @create 2023-01-13-22:46
 */
@WebServlet("/addart")
public class AddArticleServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String msg = "未知参数addart";
        int data = 0;

        //验证当前的登录状态
        UserInfo userInfo = SessionUtils.getLoginUser(req );
        if(userInfo!=null){
            //1.得到前端参数进行非空校验
            String title = req.getParameter("title");
            String context = req.getParameter("context");


            if(!StrUtil.isBlank(title)&& !StrUtil.isBlank(context)){
                //2.连接数据库
                //这里要得到session中的uid,插入数据时用
//                HttpSession session =req.getSession(false);//只有登陆时设置为true
//                int uid =-1;
//                //判断当前是否为登录状态
//                if(session!=null && session.getAttribute(AppVar.SESSION_USERINFO_KEY)!=null){
//                    //从session中得到一个对象，从对象中得到数据
//                    uid= ((UserInfo)session.getAttribute(AppVar.SESSION_USERINFO_KEY)).getUid();
//                }else {
//                    msg = "当前用户未登录";
//                }
                //2.1得到connect
                Connection connection = DBUtils.getConnection();
                //2.2拼接sql,得到执行器
                String sql = "insert into article(title,context,uid) values (?,?,?)";
                PreparedStatement statement = connection.prepareStatement(sql);
                //2.3设置占位符，得到结果集
                statement.setString(1,title);
                statement.setString(2,context);
                int uid = userInfo.getUid();
                statement.setInt(3,uid);
                data = statement.executeUpdate();
                //2.4关闭资源
                DBUtils.close(null,statement,connection);
                msg = "成功抵达";
            }else {
                msg = "参数有误";
            }
        }else {
            msg = "addarticle当前用户未登录";
        }

        //3.将结果返回给前端
        resp.setContentType(AppVar.RESP_JSON_UTF8);
        resp.getWriter().println(
                JSONUtil.toJsonStr(
                        ResultUtils.toResult(200,data,msg)
                )
        );
    }
}
